<template>
  <div class="container">
    <div
      style="
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: -1;
        background: #fff;
      "
    ></div>
    <div
      class="ddd"
      id="ddd"
      ref="signImgRef"
      style="position: fixed; top: 0; left: 0; z-index: -2"
    >
      <div class="hbox">
        <div class="dtop">托管合同</div>
        <div class="db1 db2">甲方：</div>
        <div class="db1">邮箱：{{ infos.email }}</div>
        <div class="db1">地址：</div>
        <div class="db1">{{ currentAddress }}</div>
        <div class="db1 db2">乙方：微澜AI智能合约托管平台</div>
        <div class="db1 db2">甲方：</div>
        <div class="db1">
          1、本人自愿将okex账户（币安账户）资产托管给第三方平台微澜AI智能合约托管平台做运营管理，并非经任何人诱使，平台方已明确告知我任何投资都有风险。
        </div>
        <div class="db1">
          2、本人资产为自己个人资产，并非信用卡套现、抵押贷款等有风险性资产，平台方已告知本人不得使用如上资产做投资，如果本人擅自用如上资产做投资，造成的一切后果由本人承担。
        </div>
        <div class="db1">3、因市场行情不同，本人接受平台方运营的收益结果。</div>
        <div class="db1">
          4、本人承诺每个月会将盈利部分转出合约账户，只在托管的账户里留存对应的本金，如没有按此操作造成的损失，由本人承担。
        </div>
        <div class="db1 db2">乙方：</div>
        <div class="db1">
          1、本平台为第三方资产托管平台，负责对用户托管给本平台的资产进行运营管理，在本平台自主研发的AI智能管理的系统内托管的账户，收益随市场行情波动，约为1%-10%不等。
        </div>
        <div class="db1">
          2、在正常行情下，造成用户资产爆仓，平台在减去累计收益后，承诺用保障金账户内的资产赔付用户本金的70%，30%由用户自行承担。例：用户初始账户资产为2000U，三个月累计收益为600U，若出现爆仓，平台赔付金额为：（2000-600）*0.7=980U.
        </div>
        <div class="db1">
          3、若因为极端行情，出现大面积爆仓，平台将启动保险金账户的全部金额，对实际本金受损的用户进行平均赔付。例：平台保险金账户累计金额为500000U，本金实际受损用户为1000人，则每人赔付500000/1000=500U。若保险金账户内累计资产够全部本金受损账户的70%，则按照70%进行赔付。
        </div>
        <div class="db1">
          4、保险金账户为平台50%分润中的10%累积而成，公开透明，会在平台显著位置呈现供用户检阅。
        </div>
        <div class="dbot">
          <div class="dt">
            <div class="dt1">甲方：</div>
            <img :src="signImg64" alt="" />
            <div class="dt1">日期：{{ getNowFormatDate() }}</div>
          </div>
          <div class="dt">
            <div class="dt1">已方：</div>
            <div class="dt1">微澜AI智能合约托管平台</div>
            <div class="dt1">日期：{{ getNowFormatDate() }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="cheader2">
      <van-icon
        @click="goBack"
        class="chl"
        name="arrow-left"
        color="#000"
        size="20"
      />
      <div class="chtitle">AI智能交易</div>
      <div class="djbox"></div>
    </div>

    <div class="mbox">
      <van-tabs
      v-model:active="tabIndex"
      sticky
      shrink
      title-inactive-color="#878B97"
      title-active-color="#000"
      color="#000"
      line-width="20px"
      background="#fff"
    >
      <van-tab title="OKX">
      </van-tab>
    </van-tabs>
      <div class="mul" v-if="aiList.length">
        <div class="mli" v-for="item in aiList" :key="item.id">
          <div class="mtop">
            <div class="mt1">
              <div class="mt1-3">{{item.platformId === OKX_ID ? 'OKX' : 'other'}}平台</div>
              <img :src="item.image" alt="" />
              <div class="mt1-1">{{ item.symbolName }}</div>
              <div class="mt1-2">{{ item.multiple }}X {{ item.side }}</div>
            </div>
            <div class="mt2" @click="handleOpen(item)">
              {{ item.switchStatus || "开启" }}
            </div>
          </div>
          <div class="mmain">
            <div class="mmitem">
              <div class="mm1">持仓量</div>
              <div class="mm2">{{ item.numNow }}</div>
            </div>
            <div class="mmitem">
              <div class="mm1">持仓总额</div>
              <div class="mm2">{{ item.valueNow }}</div>
            </div>
            <div class="mmitem">
              <div class="mm1">持仓均价</div>
              <div class="mm2">{{ item.avgOpen }}</div>
            </div>
            <div class="mmitem">
              <div class="mm1">总盈利</div>
              <div class="mm2">{{ item.profitTotal }}</div>
            </div>
            <div class="mmitem">
              <div class="mm1">持仓张数</div>
              <div class="mm2">{{ item.sheetNumNow }}</div>
            </div>
            <div class="mmitem">
              <div class="mm1">收益率</div>
              <div :class="+item.profitRate >= 0 ? 'mm2 active' : 'mm2 ared'">
                {{
                  +item.profitRate > 0
                    ? "+" + item.profitRate
                    : item.profitRate
                }}%
              </div>
            </div>
            <div class="mmitem">
              <div class="mm1">保证金</div>
              <div class="mm2">{{ item.margin }}</div>
            </div>
            <div class="mmitem">
              <div class="mm1">当前价格</div>
              <div class="mm2">{{ item.price }}</div>
            </div>
          </div>
        </div>
      </div>
      <van-empty
        v-else
        description="暂无数据"
        image-size="100"
        :image="require('@/assets/images/null.png')"
      />
    </div>
    <van-dialog
      v-model:show="signShow"
      title="托管合同"
      show-cancel-button
      confirmButtonText="签名"
      @confirm="handleSign"
    >
      <div class="dbox">
        <div class="db1 db2">甲方：</div>
        <div class="db1">邮箱：{{ infos.email }}</div>
        <div class="db1">地址：</div>
        <div class="db1">{{ currentAddress }}</div>
        <div class="db1 db2">乙方：微澜AI智能合约托管平台</div>
        <div class="db1 db2">甲方：</div>
        <div class="db1">
          1、本人自愿将okex账户（币安账户）资产托管给第三方平台微澜AI智能合约托管平台做运营管理，并非经任何人诱使，平台方已明确告知我任何投资都有风险。
        </div>
        <div class="db1">
          2、本人资产为自己个人资产，并非信用卡套现、抵押贷款等有风险性资产，平台方已告知本人不得使用如上资产做投资，如果本人擅自用如上资产做投资，造成的一切后果由本人承担。
        </div>
        <div class="db1">3、因市场行情不同，本人接受平台方运营的收益结果。</div>
        <div class="db1">
          4、本人承诺每个月会将盈利部分转出合约账户，只在托管的账户里留存对应的本金，如没有按此操作造成的损失，由本人承担。
        </div>
        <div class="db1 db2">乙方：</div>
        <div class="db1">
          1、本平台为第三方资产托管平台，负责对用户托管给本平台的资产进行运营管理，在本平台自主研发的AI智能管理的系统内托管的账户，收益随市场行情波动，约为1%-10%不等。
        </div>
        <div class="db1">
          2、在正常行情下，造成用户资产爆仓，平台在减去累计收益后，承诺用保障金账户内的资产赔付用户本金的70%，30%由用户自行承担。例：用户初始账户资产为2000U，三个月累计收益为600U，若出现爆仓，平台赔付金额为：（2000-600）*0.7=980U.
        </div>
        <div class="db1">
          3、若因为极端行情，出现大面积爆仓，平台将启动保险金账户的全部金额，对实际本金受损的用户进行平均赔付。例：平台保险金账户累计金额为500000U，本金实际受损用户为1000人，则每人赔付500000/1000=500U。若保险金账户内累计资产够全部本金受损账户的70%，则按照70%进行赔付。
        </div>
        <div class="db1">
          4、保险金账户为平台50%分润中的10%累积而成，公开透明，会在平台显著位置呈现供用户检阅。
        </div>
      </div>
    </van-dialog>
    <Sign
      v-if="signRefShow"
      @close="signRefShow = false"
      @autographConfirm="signConfirm"
    />
    <van-dialog
      v-model:show="uploadShow"
      show-cancel-button
      confirmButtonText="上传"
      @confirm="uploadSingImg"
    >
      <div style="padding: 10px; max-height: 60vh; overflow-y: scroll">
        <img style="width: 100%" v-if="uploadImg64" :src="uploadImg64" alt="" />
      </div>
    </van-dialog>
  </div>
</template>

<script setup lang='ts'>
import { reactive, onMounted, ref, onUnmounted, computed, nextTick, watch, watchEffect } from "vue";
import { useRouter, useRoute } from "vue-router";
import http from "@/utils/http";
import { Dialog, Toast } from "vant";
import { useStore } from "@/store";
import { SOCKET_URL } from "@/utils/common";
import html2canvas from "html2canvas";
import Sign from "@/components/Sign";
import { OKX_ID } from "@/utils/common";

const store = useStore();
const route = useRoute();
const router = useRouter();
const signShow = ref(false);
const signRefShow = ref(false);
const uploadShow = ref(false);
const signImg64 = ref("");
const uploadImg64 = ref("");
const signImgRef = ref(null);
const tabIndex = ref(0)

const goBack = () => {
  router.go(-1);
};
const aiList = ref<any>([]);
const allList = ref<any>([])
const getNowFormatDate = () => {
  let date = new Date();
  let seperator1 = ".";
  let year = date.getFullYear();
  let month: any = date.getMonth() + 1;
  let strDate: any = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
};
let websocket: any;
const token = computed(() => store.state.users.token);
const infos = computed(() => store.state.users.infos);
const currentAddress = computed(() => store.state.users.currentAddress);
onMounted(() => {
  if(infos.value.isLogin !== false){
    store.dispatch("users/updateUserInfo");
  }
  handleWebSocket();
});
// onMounted(() => {
//   store.dispatch('users/updateUserInfo')
//   handleWebSocket();
// });
onUnmounted(() => {
  websocket && websocket.close();
});
const handleWebSocket = () => {
  websocket && websocket.close();
  websocket = new WebSocket(
    `${SOCKET_URL}/strategy/ws/info?access_token=${token.value}`
  );
  websocket.onopen = () => {
    websocket.send(
      JSON.stringify({
        type: "subscribe",
        params: {
          requestApi: "strategy_contract_list",
          requestParam: {
            groupId: route.query.id,
          },
        },
      })
    );
  };
  websocket.onmessage = (data: any) => {
    if (data.data) {
      allList.value = JSON.parse(data.data);
    }
  };
};

const handleSign = () => {
  signRefShow.value = true;
};
const signConfirm = (url: any) => {
  signRefShow.value = false;
  signImg64.value = url.baseCode;
  createSignImg();
};
const createSignImg = () => {
  // setTimeout(() => {
  nextTick(() => {
    const htmlDom: any = signImgRef.value;
    console.log("dom", htmlDom.offsetLeft);
    console.log("dom", htmlDom.offsetTop);
    html2canvas(htmlDom, {
      // scale: 1,
      x: htmlDom.offsetLeft, //传入x和y长度，拒绝空白图片
      y: htmlDom.offsetTop,
      allowTaint: false, //允许污染
      taintTest: true, //在渲染前测试图片
      useCORS: true, //使用跨域(当allowTaint为true时这段代码没什么用)
      background: "#000",
      scale: 2, // 处理模糊问题
      dpi: 300, // 处理模糊问题
    }).then((canvas: any) => {
      // 新增代码 返回图片的URL,设置为png格式
      var dataUrl = canvas.toDataURL("image/png");
      uploadImg64.value = dataUrl;
      uploadShow.value = true;
    });
  });
  // }, 100);
};
const uploadSingImg = () => {
  console.log("上传");
  let formData = new FormData();
  formData.append("file", base64ToFile(uploadImg64.value, "file"));
  http.post("user/user_agreement/upload", formData).then((res: any) => {
    if(res.code === 0){
      store.dispatch('users/updateUserInfo')
      Toast('上传成功，请重新开启策略')
    }
  });
};
const base64ToFile = (dataurl: string, filename: string) => {
  let arr: any = dataurl.split(",");
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
};

const handleOpen = (item: any) => {
  if (infos.value.isAgreement === 0) {
    signShow.value = true;
    return;
  } else {
    if (!item.switchStatus) {
      Dialog({
        title: "提示",
        showCancelButton: true,
        message: "确定开启策略?",
      })
        .then(() => {
          http
            .post("strategy/app/contract/open/" + item.id)
            .then((res: any) => {
              if (res.code === 0) {
                Toast("策略已开启");
                // getAiList();
                handleWebSocket();
              }
            });
        })
        .catch(() => {
          // on cancel
        });
    }
  }
};


watchEffect(()=>{
  if(tabIndex.value === 0){
    aiList.value = allList.value.filter((v:any)=>v.platformId === OKX_ID)
  }
})


</script>

  <style lang="scss" scoped>
.cheader2 {
  z-index: 1001;
  width: 100%;
  height: 45px;
  background-color: #fff;
  font-size: 16px;
  color: #000;
  position: fixed;
  top: 0;
  left: 0;
  .chl {
    position: absolute;
    left: 16px;
    top: 50%;
    text-align: center;
    transform: translateY(-50%);
  }
  .chtitle {
    position: absolute;
    left: 50%;
    top: 50%;
    text-align: center;
    transform: translate(-50%, -50%);
  }
  .djbox {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;
    img {
      width: 16px;
      margin-right: 4px;
    }
    div {
      font-size: 13px;
      color: #666;
    }
  }
}
.mbox {
  margin-top: 45px;
  padding: 0px 2px;
  .mli {
    padding: 0 14px;
    // background: url("@/assets/images/biankuang2.png") center no-repeat;
    // background-size: 100% 100%;
    overflow: hidden;
    margin-top:10px;
    .mtop {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 40px;
      border-bottom: 1px solid #ddd;
      .mt1 {
        display: flex;
        align-items: flex-end;
        img {
          width: 14px;
          border-radius: 50%;
        }
        .mt1-1 {
          font-size: 15px;
          color: #000;
          margin: 0 6px;
        }
        .mt1-2 {
          font-size: 12px;
          color: #36b4ea;
        }
        .mt1-3{
          font-weight: 600;
          margin-right: 4px;
        }
      }
      .mt2 {
        width: 70px;
        height: 24px;
        border-radius: 4px 0px 4px 0px;
        background-color: #36b4ea;
        color: rgba(245, 245, 245, 1);
        font-size: 12px;
        text-align: center;
        line-height: 24px;
      }
    }
    .mmain {
      display: flex;
      flex-wrap: wrap;
      padding: 20px 0 0;
      .mmitem {
        width: 25%;
        flex: 0 0 25%;
        display: flex;
        flex-direction: column;
        margin-bottom: 16px;
        &:nth-child(4n-2) {
          text-indent: 10px;
        }
        &:nth-child(4n-1) {
          text-indent: 30px;
        }
        &:nth-child(4n) {
          text-align: right;
        }
        .mm1 {
          font-size: 12px;
          color: #666;
          margin-bottom: 10px;
        }
        .mm2 {
          font-size: 12px;
          color: #000;
        }
      }
    }
  }
}
.active {
  color: #36b4ea !important;
}
.ared {
  color: #d75656 !important;
}
.dbox {
  padding: 20px 14px;
  font-size: 13px;
  color: #000;
  line-height: 24px;
  text-align: justify;
  max-height: 50vh;
  overflow-y: scroll;
  .dtop {
    font-size: 15px;
    font-weight: 600;
    text-align: center;
    margin-bottom: 20px;
  }
  .db1 {
    word-wrap: break-word;
  }
  .db2 {
    font-weight: 600;
    color: #333;
  }
  .dbot {
    display: flex;
    margin-top: 30px;
    .dt {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .dt1 {
        font-size: 13px;
        color: #000;
      }
      img {
        width: 140px;
        // height:40px;
        // border:1px solid red;
      }
    }
  }
}
#ddd {
  // display: none;
  // opacity: 0;
}
.hbox {
  padding: 20px 10px;
  font-size: 13px;
  color: #000;
  line-height: 24px;
  text-align: justify;
  .dtop {
    font-size: 15px;
    font-weight: 600;
    text-align: center;
    margin-bottom: 20px;
  }
  .db1 {
    word-wrap: break-word;
  }
  .db2 {
    font-weight: 600;
    color: #333;
  }
  .dbot {
    display: flex;
    margin-top: 30px;
    .dt {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .dt1 {
        font-size: 13px;
        color: #000;
      }
      img {
        width: 140px;
        // height:40px;
        // border:1px solid red;
      }
    }
  }
}
</style>
